<template>
  <div class="container">
    <van-nav-bar :title="title" fixed class="titleStyle" left-arrow @click-left="onClickLeft" />
    <van-button class="saveBtn" type="primary" native-type="submit" @click="handleSubmit()">保存</van-button>
    <div class="publicBox formDivBox">
      <van-form ref="form">
        <van-field v-if="detailsObj.repairMethod === 1" v-model="ruleForm.groupName" readonly clickable placeholder="请选择" name="groupName" label="班组" :rules="[{ required: true, message: '请选择班组', trigger: 'blur' }]" @click="showGroup = true" />
        <van-field-checkbox v-if="detailsObj.repairMethod === 1" v-model="userLists" label="责任人" placeholder="请选择责任人" :columns="userListAll" :option="{label:'userName',value:'userId'}" />
        <van-field v-if="detailsObj.repairMethod === 2" v-model="ruleForm.companyName" readonly clickable placeholder="请选择" name="companyName" label="维保商" :rules="[{ required: true, message: '请选择维保商', trigger: 'blur' }]" @click="showMaintainDealer = true" />
        <van-field v-model="ruleForm.expectedResolutionTime" label="期望解决时间" name="expectedResolutionTime" size="mini" readonly @click="showTime = true" />
      </van-form>
    </div>
    <!--  时间选择 -->
    <van-popup v-model="showTime" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker v-model="currentDate" type="date" @confirm="onTimeChange" @cancel="showTime = false" />
    </van-popup>
    <!-- 班组选择 -->
    <van-popup v-model="showGroup" position="bottom">
      <van-picker title="班组选择" show-toolbar :columns="getGroupList" @confirm="onGroup" @cancel="showGroup = false" />
    </van-popup>
    <!-- 维保商 -->
    <van-popup v-model="showMaintainDealer" position="bottom">
      <van-picker title="维保商" show-toolbar :columns="maintainerData" @confirm="onMaintainerData" @cancel="showMaintainDealer = false" />
    </van-popup>
  </div>
</template>
<script>
import { myFunction } from '@/utils/function'
import vanFieldCheckbox from '@/components/selectUser'
export default {
  name: 'TaskAssignment',
  components: { vanFieldCheckbox },
  data () {
    return {
      title: '',
      currentDate: new Date(),
      userListAll: [],
      userList: [],
      userLists: [],
      ruleForm: {
        groupId: '', // 班组
        groupName: '',
        maintainDealerId: '', // 维保商主键
        companyName: '',
        expectedResolutionTime: '',
        id: '',
        userList: []
      },
      show: false,
      code: localStorage.getItem('code'),
      list: [],
      loading: false,
      isLoading: false,
      detailsObj: {},
      showTime: false,
      showUser: false,
      showGroup: false,
      getGroupList: [],
      getGroupLists: [],
      showMaintainDealer: false,
      maintainerData: [],
      maintainerDatas: []
    }
  },
  watch: {},
  created () {},
  mounted () {
    this.getData()
  },
  methods: {
    formatter (value) {
      return value.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3')
    },
    async getData () {
      this.detailsObj = this.$store.state.data
      this.title =
        this.detailsObj.repairMethod === 1 ? '任务下达-内修' : '任务下达-外修'
      if (this.detailsObj.repairMethod === 1) {
        await this.getGroupInfo()
      } else {
        await this.getMaintainer(this.detailsObj.equipId)
      }
      setTimeout(() => {
        this.ruleForm = { ...this.ruleForm, ...this.detailsObj }
        // 添加默认班组后带出默认维修人
        this.onGroup(this.ruleForm.groupName)
      })
    },
    /* 获取所有班组 */
    async getGroupInfo () {
      const res = await this.$axios.get(`/dobo-equip/repair/order/getGroup`)
      if (res && res.data.code === 200) {
        this.getGroupLists = res.data.data
        res.data.data.forEach((item) => {
          this.getGroupList.push(item.groupName)
          if (item.groupUsers) {
            this.userListAll = item.groupUsers
            item.groupUsers.forEach((item) => {
              this.userLists.push(item.userId)
              this.userList.push(item.userName)
            })
          }
        })
      }
    },
    /* 班组选择 */
    onGroup (e) {
      this.getGroupLists.forEach((item) => {
        if (item.groupName === e) {
          this.ruleForm.groupId = item.groupId
          this.ruleForm.groupName = item.groupName
          if (item.groupUsers) {
            this.userListAll = item.groupUsers
            item.groupUsers.forEach((item) => {
              this.userLists.push(item.userId)
              this.userList.push(item.userName)
            })
          }
        }
      })
      this.showGroup = false
    },
    /* 获取维保商 */
    async getMaintainer (equipId) {
      const res = await this.$axios.get(
        `/dobo-equip/repair/order/getMaintainDealerByEquip?equipId=${equipId}`
      )
      if (res?.data.code === 200) {
        this.maintainerDatas = res.data.data
        res.data.data.forEach((item) => {
          this.maintainerData.push(item.companyName)
        })
        /* 如果存在维修记录，则自动带出最近一次外修时对应的维保商（如果维保商已停用，则不带出） */
        this.maintainerData.forEach((item) => {
          if (item.isSelect === 1) {
            this.ruleForm.maintainDealerId = item.maintainDealerId
            this.ruleForm.companyName = item.companyName
          }
        })
      }
    },
    /* 维保商选择 */
    onMaintainerData (e) {
      this.maintainerDatas.forEach((item) => {
        if (item.companyName === e) {
          this.ruleForm.maintainDealerId = item.maintainDealerId
          this.ruleForm.companyName = item.companyName
        }
      })
      this.showMaintainDealer = false
    },
    /* 时间选择赋值 */
    onTimeChange (value) {
      setTimeout(() => {
        this.ruleForm.expectedResolutionTime = myFunction(value)
        this.showTime = false
      }, 500)
    },
    handleSubmit () {
      this.$refs.form
        .validate()
        .then(() => {
          this.$dialog
            .confirm({
              title: '提示',
              message: '是否确认提交？'
            })
            .then(() => {
              this.submitApi()
            })
            .catch(() => {
              return false
            })
        })
        .catch(() => {})
    },
    submitApi () {
      const toast = this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: '提交中...',
        forbidClick: true,
        loadingType: 'spinner'
      })
      let url = ''
      if (this.title === '任务下达-内修') {
        const list = []
        this.userListAll.forEach((item) => {
          this.userLists.forEach((itx) => {
            if (item.userId === itx) {
              list.push({ userId: item.userId, userName: item.userName })
            }
          })
        })
        this.ruleForm.userList = list
        url = '/dobo-equip/repair/order/arrangeIn'
      } else {
        url = '/dobo-equip/repair/order/arrangeOut'
      }
      this.$axios
        .post(url, this.ruleForm)
        .then((res) => {
          if (res.data.code === 200) {
            toast.clear()
            this.$dialog
              .alert({
                title: '提示',
                message: '提交成功!'
              })
              .then(() => {
                this.$router.push('/eqRepairRequest')
              })
              .catch(() => {})
          } else {
            this.$toast.fail(res.data.msg)
            setTimeout(() => {
              toast.clear()
              this.$router.push('/eqRepairRequest')
            }, 1000)
          }
        })
        .catch(() => {})
    },
    // 返回
    onClickLeft () {
      const { query } = this.$route
      if (query.path) {
        this.$router.push(`/${query.path}`)
      } else {
        this.$router.push('/eqRepairRequest')
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.container {
  .inputRightFont {
    overflow: hidden;
    height: 40px;
    line-height: 40px;
    .sp {
      padding-left: 5px;
    }
  }
  .formDivBox {
    .van-field {
      border: 1px solid #f5f5f5;
    }
    .pStyle {
      height: 35px;
      line-height: 35px;
      background: #f5f5f5;
      text-align: center;
    }
    .extensionDiv {
      overflow: hidden;
      .van-field {
        width: 50%;
        float: left;
        border: 1px solid #f5f5f5;
      }
    }
  }
}
</style>
<style lang='scss'>
</style>
